package com.hu.gulimallware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.gulimallcommon.utils.PageUtils;
import com.hu.gulimallcommon.utils.Query;
import com.hu.gulimallcommon.utils.R;
import com.hu.gulimallware.dao.WmsWareSkuDao;
import com.hu.gulimallware.entity.WmsWareSkuEntity;
import com.hu.gulimallware.feign.ProductFeignService;
import com.hu.gulimallware.service.WmsWareSkuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;



@Service("wmsWareSkuService")
public class WmsWareSkuServiceImpl extends ServiceImpl<WmsWareSkuDao, WmsWareSkuEntity> implements WmsWareSkuService {
    @Autowired
    ProductFeignService productFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WmsWareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String)  params.get("skuId");
        if(StringUtils.isNotEmpty(skuId)){
            if(!"0".equals(skuId)){
                queryWrapper.eq("sku_id",skuId);
            }

        }
        String wareId = (String)  params.get("wareId");
        if(StringUtils.isNotEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<WmsWareSkuEntity> page = this.page(
                new Query<WmsWareSkuEntity>().getPage(params),queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WmsWareSkuEntity> wmsWareSkuEntities = baseMapper.selectList(new QueryWrapper<WmsWareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(wmsWareSkuEntities!=null && wmsWareSkuEntities.size()>0){
            baseMapper.addStock(skuId,wareId,skuNum);
        }else {
            WmsWareSkuEntity wmsWareSkuEntity = new WmsWareSkuEntity();
            wmsWareSkuEntity.setSkuId(skuId);
            wmsWareSkuEntity.setWareId(wareId);
            wmsWareSkuEntity.setStock(skuNum);
            wmsWareSkuEntity.setStockLocked(0);
            // 远程调用失败，整个事务无须回滚
            //1. 自己catch 异常

            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> pmsSkuInfo = (Map<String,Object>)info.get("pmsSkuInfo");
                if (info.getCode()==0){
                    wmsWareSkuEntity.setSkuName((String) pmsSkuInfo.get("skuName"));
                }
            } catch (Exception e) {
            }

            baseMapper.insert(wmsWareSkuEntity);
        }
    }

}